package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(timeout = 200000)
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser queryWithMaxScore(Long userId) {
        // 查询今日佳人:db.recommend_user.find({userId:1}).sort({score:-1}).limit(1)
        //1. 查询条件: userId
        Query query = new Query(Criteria.where("userId").is(userId));
        //2. 排序、limit
        query.with(Sort.by(Sort.Order.desc("score"))).limit(1);
        //3. 条件查询
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        return recommendUser;
    }

    @Override
    public PageResult queryRecommendation(Long userId, Integer page, Integer pagesize) {
        //1. 构造条件:db.recommend_user.find({userId:1}).sort({score:-1}).limit(2).skip(0)
        Query query = new Query(
            Criteria.where("userId").is(userId)
        );
        //1.1 设置排序
        query.with(Sort.by(Sort.Order.desc("score")));
        //1.2 设置分页
        query.limit(pagesize).skip((page-1)*pagesize);
        //2. 根据条件分页查询
        List<RecommendUser> list = mongoTemplate.find(query, RecommendUser.class);
        //3. 根据条件统计
        long count = mongoTemplate.count(query, RecommendUser.class);
        //4. 返回分页对象
        return new PageResult(page,pagesize, (int) count,list);
    }


    @Override
    public Long queryScore(Long userId, Long recommendUserId) {
        // db.recommend_user.find({userId:1,recommendUserId:57})
        // 创建条件对象
        Query query = new Query(
            Criteria.where("userId").is(userId)
                .and("recommendUserId").is(recommendUserId)
        );
        query.limit(1);
        // 条件查询
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if (recommendUser == null) {
            return 70L;
        }
        // 返回缘分值
        return recommendUser.getScore().longValue();
    }
}
